<?php
declare(strict_types=1);

namespace Zms\Unit;

/**
 * 日期时间转换工具
 */
class Timeformat
{
    /**
     * 秒数转时分格式
     * 如传入36456  返回:0年0天 10小时7分36秒
     * @param  $time int
     * @param bool $exclude_excess
     * @return string
     */
    public static function Sec2Time(int $time, bool $exclude_excess = false): string
    {
        $value = ['years' => 0, 'days' => 0, 'hours' => 0, 'minutes' => 0];
        if ($time >= 31556926) {
            $value['years'] = floor($time / 31556926);
            $time = ($time % 31556926);
        }
        if ($time >= 86400) {
            $value['days'] = floor($time / 86400);
            $time = ($time % 86400);
        }
        if ($time >= 3600) {
            $value['hours'] = floor($time / 3600);
            $time = ($time % 3600);
        }
        if ($time >= 60) {
            $value['minutes'] = floor($time / 60);
            $time = ($time % 60);
        }
        $value['seconds'] = floor($time);
        return $value['years'] . '年' . $value['days'] . '天 ' . $value["hours"] . '小时' . $value['minutes'] . '分' . $value['seconds'] . '秒';
    }


    /**
     * 转换时间显示
     * 如传入  time()-2345  返回39分钟前
     * @param int $timestamp 时间戳
     * @param string $format 转换格式
     * @param bool $convert 是否需要转换
     * @return string
     */
    public static function show(int $timestamp, string $format = 'Y-m-d H:i:s', bool $convert = true): string
    {
        $thistime = time();
        if ($convert === false) {
            return date($format, $timestamp);
        }
        $second = $thistime - $timestamp;
        if ($second < 10) {
            return '刚刚';
        } elseif ($second < 60) {
            return "{$second}秒前";
        } elseif ($second < 3600) {
            return floor($second / 60) . "分钟前";
        } elseif ($second < 86400) {
            if (date("Y-m-d", $thistime) === date("Y-m-d", $timestamp)) {//今天
                return "今天" . date("m:d:s", $timestamp);
            }
            return "昨天" . date("m:d:s", $timestamp);
        }
        return date($format, $timestamp);
    }
}